using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.Infrastructrue.Utils;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;
using Yitter.IdGenerator;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	/// <summary>
	/// 创建用户命令处理器
	/// </summary>
	public class CreateUserCommandHandler : IRequestHandler<CreateUserCommand, UserDto>
	{
		private readonly IBaseRepository<User> _userRepo;
		private readonly IBaseRepository<UserRole> _userRoleRepo;

		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="userRepo">用户仓储</param>
		/// <param name="userRoleRepo">用户角色关联仓储</param>
		public CreateUserCommandHandler(IBaseRepository<User> userRepo, IBaseRepository<UserRole> userRoleRepo)
		{
			_userRepo = userRepo;
			_userRoleRepo = userRoleRepo;
		}

		/// <summary>
		/// 处理创建用户命令
		/// </summary>
		/// <param name="request">创建用户命令</param>
		/// <param name="cancellationToken">取消令牌</param>
		/// <returns>创建的用户DTO</returns>
		/// <exception cref="ArgumentException">当用户名或密码为空时抛出</exception>
		/// <exception cref="InvalidOperationException">当用户名已存在时抛出</exception>
		public async Task<UserDto> Handle(CreateUserCommand request, CancellationToken cancellationToken)
		{
			// 验证用户名
			if (string.IsNullOrWhiteSpace(request.UserName))
			{
				throw new ArgumentException("用户名不能为空", nameof(request.UserName));
			}

			if (string.IsNullOrWhiteSpace(request.Password))
			{
				throw new ArgumentException("密码不能为空", nameof(request.Password));
			}

			// 检查用户名是否已存在
			var existingUser = await _userRepo.GetModel(x => 
				x.UserName == request.UserName && !x.IsDeleted);
			if (existingUser != null)
			{
				throw new InvalidOperationException($"用户名 '{request.UserName}' 已存在");
			}

			// 创建用户
			var user = new User
			{
				UserId = YitIdHelper.NextId(),
				UserName = request.UserName.Trim(),
				PasswordHash = PasswordHasher.HashPassword(request.Password),
				Email = request.Email,
				FullName = request.FullName,
				Phone = request.Phone,
				EmployeeId = request.EmployeeId,
				IsActive = request.IsActive,
				IsDeleted = false,
				CreatedAt = DateTime.Now,
				UpdatedAt = DateTime.Now
			};

			await _userRepo.InsertAsync(user);

			// 分配角色
			if (request.RoleIds != null && request.RoleIds.Any())
			{
				var userRoles = request.RoleIds.Distinct()
					.Select(roleId => new UserRole
					{
						UserRoleId = YitIdHelper.NextId(),
						UserId = user.UserId,
						RoleId = roleId
					})
					.ToList();
				if (userRoles.Any())
				{
					await _userRoleRepo.AddRangeAsync(userRoles);
				}
			}

			return new UserDto
			{
				UserId = user.UserId,
				UserName = user.UserName,
				Email = user.Email,
				FullName = user.FullName,
				Phone = user.Phone,
				EmployeeId = user.EmployeeId,
				IsActive = user.IsActive,
				LastLoginAt = user.LastLoginAt,
				LastLoginIp = user.LastLoginIp,
				CreatedAt = user.CreatedAt,
				UpdatedAt = user.UpdatedAt
			};
		}
	}
}

